<template>
  <div class="container" v-loading="loading" element-loading-text="拼命加载中">
    <!-- 左侧区域 -->
    <div class="left-panel">
      <h3 class="el-icon-s-tools" style="color: #404062">配置</h3>
      <el-form :model="form" label-width="80px" :rules="rules" ref="formRef">
        <el-form-item label="提示词" prop="prompt">
          <el-input
              type="textarea"
              :rows="5"
              placeholder="请输入提示词"
              maxlength="6000"
              show-word-limit
              v-model="form.prompt">
          </el-input>
        </el-form-item>
        <el-form-item label="尺寸">
          <el-radio-group v-model="form.size">
            <el-radio
                v-for="option in sizeOptions"
                :key="option.value"
                :label="option.value"
                style="border: 1px #cccccc solid;padding: 10px;width: 100px;border-radius: 10px;margin: 5px"
            >
              {{ option.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="种子值">
          <el-slider
              v-model="form.seed"
              :max="4294967289"
              show-input
              input-size="mini"
          ></el-slider>
        </el-form-item>
        <el-button
            style="background-color: #605be8;width: 100%"
            type="primary"
            @click="submitForm"
            :disabled="loading"
        >
          开始生成
        </el-button>
      </el-form>
    </div>

    <!-- 右侧区域 -->
    <div class="right-panel">
      <el-row :gutter="20" v-if="images.length">
        <el-col
            v-for="(image, index) in filteredImages"
            :key="index"
            :span="8"
        >
          <el-card class="image-card">
            <el-image
                alt="Generated Image" class="image-preview"
                :src="image.imageUrl"
                :preview-src-list="[image.imageUrl]">
            </el-image>
            <p>{{ image.description }}</p>
            <p>{{ image.createTime }}</p>
            <div class="card-body">
              <el-button plain type="primary" @click="downloadImage(image.imageUrl)">
                下载
              </el-button>
              <el-button plain type="danger" @click="removeImage(image.id)">
                移除
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <el-empty v-else description="请生成图片吧"></el-empty>
    </div>
  </div>
</template>

<script>
import {generatorImage, imagList, removeImage} from "@/api/request/AIToolRequest";

export default {
  data() {
    return {
      userInfo: {},
      form: {
        prompt: "",
        size: "1024*1024",
        seed: 1,
      },
      searchKeyword: "",
      images: [], // 存储生成的图像数据
      loading: false, // 加载状态
      sizeOptions: [
        {label: "512*1024", value: "512*1024"},
        {label: "768*512", value: "768*512"},
        {label: "768*1024", value: "768*1024"},
        {label: "1024*576", value: "1024*576"},
        {label: "576*1024", value: "576*1024"},
        {label: "1024*1024", value: "1024*1024"},
      ],
      rules: {
        prompt: [{required: true, message: "提示词不能为空", trigger: "blur"}],
      },
    };
  },
  computed: {
    // 过滤生成的图像列表
    filteredImages() {
      if (!this.searchKeyword) {
        return this.images;
      }
      return this.images.filter((image) =>
          image.title.includes(this.searchKeyword)
      );
    },
  },
  methods: {
    submitForm() {
      this.$refs.formRef.validate((valid) => {
        if (!this.userInfo) {
          this.$message.warning('请先登录');
          return;
        }

        if (valid) {
          this.generateImage();
        } else {
          console.log("表单验证失败");
          return false;
        }
      });
    },
    generateImage() {
      try {
        this.loading = true; // 设置加载状态
        generatorImage({
          prompt: this.form.prompt,
          size: this.form.size,
          seed: this.form.seed,
          createUser: this.userInfo.id
        }).then(() => {
          this.imageList()
          this.loading = false; // 清除加载状态
          this.form.prompt = ''
        });
      } catch (error) {
        console.error("生成图像失败:", error);
        this.loading = false; // 清除加载状态
        this.form.prompt = ''
      }
    },
    downloadImage(url) {
      this.$confirm('确定下载图片, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (url) {
          const link = document.createElement("a");
          link.href = url;
          link.download = "generated_image.png";
          link.click();
        }
      }).catch(() => {
      });
    },
    removeImage(imageUrl) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        removeImage(imageUrl).then(res=>{
          if (res.code !== 200) {
            this.$message.error(res.msg);
            return;
          }

          this.imageList()
          this.$message.success('移除成功');
        })
      }).catch(() => {
      });
    },
    imageList() {
      if (!this.userInfo) {
        return
      }

      imagList({userId: this.userInfo.id}).then(res => {
        if (res.code !== 200) {
          this.$message.error(res.msg);
          return;
        }

        this.images = res.data
      })
    }
  },
  mounted() {
    this.userInfo = JSON.parse(localStorage.getItem('xm-user'))
    this.imageList()
  }
};
</script>

<style scoped>
.container {
  display: flex;
  justify-content: space-between;
  gap: 20px;
  height: 800px;
}

.left-panel {
  width: 300px;
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 8px;
}

.right-panel {
  flex: 1;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
}

.image-card {
  position: relative;
  overflow: hidden;
  border-radius: 8px;
}

.image-preview {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.card-body {
  padding: 10px;
}
</style>
